/*
 * 入库记录删除
 * 参数   交易码：trancode=51117
 * 
 */

package org.ccams.tran;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.ccams.domain.TpInDetail;
import org.ccams.web.WebBeanFactory;
import org.json.JSONArray;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class Tran51117 extends AbstractJsonTran{
	@SuppressWarnings("unchecked")
	public void buildJSONObject(Map model, JSONObject json,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String head = request.getParameter("head");
		String detail = request.getParameter("detail");

		
		HashMap<String, Object> jsonMap = new HashMap<String, Object>();
		boolean success = false;
		String message = "";	
		int k=0;		
		DataSourceTransactionManager txm = (DataSourceTransactionManager) WebBeanFactory.getBean("transactionManager",request);
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txm.getTransaction(def);
		try{
			if(!("".equals(head)||head == null)){		
				List<TpInDetail> list = getCcamsService().getTpindetailDao().getTpindetailById(Long.parseLong(head));
				for(TpInDetail tid : list){
					k = getCcamsService().getTpindetailDao().deleteTpindetail(tid);
				}
				k = getCcamsService().getTpinheadDao().deleteTpinhead(Long.parseLong(head));
			}
			else if(!("".equals(detail)||detail == null)){
				JSONArray detailParams = new JSONArray(detail);
				for(int i=0;i<detailParams.length();i++){
					org.json.JSONObject params = detailParams.optJSONObject(i);
					TpInDetail tid = new TpInDetail();
					tid.setNum(params.getLong("num"));
					tid.setOrd(params.getInt("ord"));
					k = getCcamsService().getTpindetailDao().deleteTpindetail(tid);
				}
			}
		}
		catch(Exception ex){
			txm.rollback(status);
	        ex.printStackTrace();
		}finally{
			txm.commit(status);
		}
		if (k == 1) {
			success = true;
			message = "删除成功";
		} else {
			success = false;
			message = "删除失败";
		}
		jsonMap.put("success", success);
		jsonMap.put("message", message);
		json.putAll(jsonMap);
	}
}
